package com.yz.xyt.controller;

import com.yz.xyt.constant.HttpStatus;
import com.yz.xyt.domain.Menu;
import com.yz.xyt.domain.ResponseResult;
import com.yz.xyt.service.IMenuService;
import com.yz.xyt.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单controller
 * @author JW.WANG
 */
@RestController
@RequestMapping("/system")
public class MenuController {

    @Autowired
    IMenuService menuService;

    @GetMapping("/getMenuList")
    public ResponseResult getMenuList(){
        Long userId = SecurityUtils.getUserId();
        List<Menu> menuList = menuService.selectUserMenusByUserId(userId);
        //过滤，获取所有一级菜单
        List<Menu> firstMenu = menuList.stream().filter(menu -> menu.getPid().equals(0)).collect(Collectors.toList());
        List<Menu> menus = new ArrayList<>();
        for (Menu root: firstMenu){
            root = menuService.getMenuTree(menuList, root);
            menus.add(root);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",menus);
        return new ResponseResult(HttpStatus.SUCCESS,"请求成功",map);
    }

    /**
     * 获取app菜单
     * @return
     */
    @GetMapping("/getAppMenus")
    public ResponseResult getAppMenus(){
        ResponseResult result = new ResponseResult();
        List<Menu> list = menuService.selectAppMenus(SecurityUtils.getUserId());
        //过滤，获取所有一级菜单
        List<Menu> firstMenu = list.stream().filter(menu -> menu.getPid().equals(0)).collect(Collectors.toList());
        List<Menu> menus = new ArrayList<>();
        for (Menu root: firstMenu){
            root = menuService.getMenuTree(list, root);
            menus.add(root);
        }
        Map<String,Object> map = new HashMap<>();
        map.put("list",firstMenu);
        result.setCode(HttpStatus.SUCCESS);
        result.setData(map);
        result.setMsg("获取菜单成功");
        return result;
    }


}
